<template>
	<view class="publishContent">
		<!-- <u-navbar title="发布内容" bgColor='#fff' leftIconColor="#000" @rightClick="rightClick" :autoBack="true"  ></u-navbar> -->

		<view class="content">
			<view class="file-box">
				  <u--input
				    placeholder="请输入内容"
				    border="surround"
				    v-model="titleValue"
				  ></u--input>
			</view>
			<view class="" style="background-color: #fff;">
				<u--textarea v-model="content" placeholder="请输入内容" confirmType='done' :maxlength='-1' height='150'></u--textarea>

				<view class="img-box" >
					<u-upload
            accept="file"
						:fileList="fileList1"
						@afterRead='afterRead'
						@delete="deletePic"
						name="1"
						ref="test"
						multiple
            :maxCount="8"
						width="240rpx" height="240rpx" uploadIcon="plus">

					</u-upload>
					<!-- #ifndef MP-WEIXIN -->
						<view class="noWeixin" @tap.stop="noWeiXinUpload" :style="{left: myLeft+'px',top:myTop+'px'}">
							<u-icon name="plus" size='52rpx' color='rgb(211, 212, 214)'></u-icon>
						</view>
					<!-- #endif -->
				</view>
			</view>
			<view class="bottom">
				<u-button text="保存草稿" style="margin-right: 60rpx;" @tap='submit(1)'></u-button>
				<u-button text="提交审核" type="primary" @tap='submit(0)'></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		sendArticle,
		articleInfo,
		footprintEditArticle
	} from '@/api/schoolEventApi.js'
	export default {
		data() {
			return {
				titleValue:'',
				content: '',
				fileList1: [],
				fullurl:[] ,
				acceptType:'image',
				uploadEl:'',
				myLeft:0,
				myTop:0,
				imageSuffix:['.png', '.jpg', '.jpeg', '.bmp', '.gif', '.webp', '.svg', '.tiff'],
				videoSuffix:['.avi','.mpeg','.wmv','.mp4','.mov','.flv','.avchd','.webm','.mkv'],
				isVideo:false,
				uploadNum:0,
				method:sendArticle,
				articleId:'',
			}
		},
		onLoad(options) {
			// #ifdef MP-WEIXIN
			    this.acceptType = 'media';
			// #endif

			if(!(options.id == '' || options.id == undefined)){
				this.method = footprintEditArticle;
				this.articleId = options.id;
				this.getArticleInfo(options.id)
			}

		},
		watch:{
			fileList1(){

				setTimeout(()=>{

					this.myLeft = this.uploadEl.offsetLeft;
					this.myTop = this.uploadEl.offsetTop;
				},10)

			}
		},
		mounted() {
     setTimeout(()=>{
        this.uploadEl = document.querySelector('.publishContent .img-box .u-upload__button');
       console.log("=this.uploadEl ",this.uploadEl )
      },500)

		},
    created() {

        setTimeout(()=>{
          this.uploadEl = document.querySelector('.publishContent .img-box .u-upload__button');
          console.log("=this.uploadEl222 ",this.uploadEl )
        },500)


    },
    methods: {
			getArticleInfo(id){
				let params = {
					article_id:id
				};
				uni.showLoading({
					title: '加载中'
				});
				articleInfo(params).then(res => {
					console.log(res)
					uni.hideLoading();
					this.titleValue = res.data.title;
					this.content = res.data.content;
					// this.fileList1 = res.data.diagram;
					if( !(res.data.video==null||res.data.video=='') ){
						this.fileList1.push({
							url: res.data.video,
							status: 'success',
							type:'video'
						})
						this.fullurl.push(res.data.video)
						this.isVideo = true;
					}

					res.data.diagram.forEach((item,index)=>{
						this.fileList1.push({url:item,type:'image',status: 'success'})
						this.fullurl.push(item)
					})


					if(res.code != 1){
						uni.showToast({
							title: res.msg,
							duration: 2000,
							icon:"none"
						});
					}
				})
			},

			submit(type){
				console.log(this.fileList1)
				console.log(this.fullurl)
				// return
				if(this.titleValue==''||this.content==''){
					uni.showToast({
						title: "标题或内容不能为空",
						duration: 2000,
						icon:'none'
					});
					return;
				}

				if(this.uploadNum != 0){
					uni.showToast({
						title: "文件上传中...",
						duration: 2000,
						icon:'none'
					});
					return;
				}

				if(type == 0){
					uni.showModal({
					    title: '提交确认',
					    content: '提交后需要后台审核\n审核成功后将自动发布!',
						confirmText:"提交",
						success:  (res)=> {
					        if (res.confirm) {
								    this.submitMet(type);
					        } else if (res.cancel) {
					            console.log('用户点击取消');
					        }
					    }
					});
				}else{
					this.submitMet(type);
				}
			},

			submitMet(type){
				let params = {
					article_id: this.articleId,
					title: this.titleValue,
					content: this.content,
					status: type,  // 是否草稿箱 0否 1是.
					diagram: this.fullurl,//摘要图，单图
				};
				console.log(params)
				uni.showLoading({
					title: '提交中'
				});
				console.log(this.method)
				this.method(params).then(resp => {
					console.log(resp)
					uni.hideLoading();
					if(resp.code == 1) {
						this.titleValue=''
						this.content= ''
						this.fileList1= []
						this.fullurl= []
						this.isVideo = false
					}
					uni.showToast({
						title: resp.msg,
						duration: 2000,
						icon:'none'
					});
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
				}).catch((err)=>{
          console.log("===return",err)
        })
			},


			noWeiXinUpload(){
				uni.showActionSheet({
					itemList: ['图片','视频'],
					success: (res) => {
						console.log(res)
						if(res.tapIndex == 0){
							this.acceptType = 'image'
						} else {
							this.acceptType = 'video'
						}
						console.log(this.acceptType)
						setTimeout(()=>{
							this.uploadEl.click();
						},300)
					}
				})
			},


			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this.fullurl.splice(event.index, 1)
				if(event.file.type=='video') this.isVideo = false;
			},

			isAssetTypeAnImage(ext,arr) {
			 return arr.indexOf(ext.toLowerCase()) == -1;
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				let flag = false;
				lists.map((item) => {
					//获取最后一个.的位置
					let index= item.name.lastIndexOf(".");
					//获取后缀
					let ext = item.name.substr(index);
					if(this.isAssetTypeAnImage(ext,[...this.imageSuffix,...this.videoSuffix])){
						uni.showToast({
							title: '文件格式不正确！',
							duration: 2000,
							icon:'none'
						});
						flag = true;
					}else if(!this.isAssetTypeAnImage(ext,[...this.videoSuffix])){
						if(this.isVideo){
							flag = true;
							uni.showToast({
								title: '视频最多只能上传一个！',
								duration: 2000,
								icon:'none'
							});
						}

						this.isVideo = true;

					}
				})


				if(flag) return;
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let fileListLen = this[`fileList${event.name}`].length
				this.uploadNum++;
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})

				})


				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url,lists[i].type)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',

					}))

					fileListLen++
				}
			},



			uploadFilePromise(url,type) {
				return new Promise((resolve, reject) => {
					let token = uni.getStorageSync('token')
					let a = uni.uploadFile({
						url: this.$httpApi+'/api/common/upload',
						filePath: url,
						name: 'file',
						formData: {

						},
						success: (res) => {
							res.data = JSON.parse(res.data)
							console.log(res)
							// let url = ;
							//获取最后一个.的位置
							let index= url.lastIndexOf(".");
							//获取后缀
							let ext = url.substr(index);
							if(res.data.code == 1){
								this.fullurl.push(res.data.data.files.fullurl)
								resolve(res.data.data)
								this.uploadNum--;
							}else{
								this.fileList1.splice(this.fileList1.length-1, 1)
								if(type=='video') this.isVideo = false;
								uni.showToast({
									title: res.data.msg,
									duration: 2000,
									icon:'none'
								});
							}
						}
					});
				})
			},
		}
	}
</script>

<style>
	.publishContent uni-button:after{
		border: none;
	}
	.content {
		background-color: #F8F8F8;
		min-height: 100vh;
		padding: 30rpx;
	}

	.img-box {
		margin: 30rpx;
		position: relative;
	}
	.publishContent /deep/.u-upload__wrap .u-upload__button{
		background-color: #f8f8f8;
		border-radius: 16rpx;
	}
	.publishContent /deep/.u-input{
		background-color: #fff;
		border-radius: 0;
		padding-top: 30rpx !important; padding-bottom: 30rpx !important;
	}
	.publishContent /deep/.u-upload__button {
		background-color: #fff;
	}
	.publishContent /deep/.u-textarea {
		border-radius: 0;
	}

	.file-box {
		width: 100%;
		border-bottom: 1px solid #eee;
	}

	.file-tip {
		background-color: #fff;
		padding: 30rpx;
		width: 620rpx;
		font-size: 28rpx;
		font-weight: 500;
		color: #999999;
	}
	.bottom{
		display: flex;
		background: #fff;
		font-size: 28rpx;
		font-weight: 500;
		color: #FFFFFF;
		padding: 20rpx;
		box-sizing: border-box;
		position:fixed;
		width: 100%;
		bottom: 0rpx;
		left: 0rpx;
	}

	.noWeixin{
		width: 240rpx;
		height: 240rpx;
		background-color: #f8f8f8;
		border-radius: 8px;
		margin: 0 16rpx 16rpx 0;
		z-index: 1;
		position: relative;

		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
	}
	.publishContent /deep/.u-upload__wrap__preview{
		z-index: 2;
	}
</style>
